﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.IService;
using MyCompany.MyProject.Model.DTO;
using MyCompany.MyProject.Model.Models;
using MyCompany.MyProject.Repository.UnitOfWork;

namespace MyCompany.MyProject.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TransactionController : ControllerBase
    {
        private readonly IBaseService<Role> roleService;
        private readonly IUnitOfWorkManage unitOfWorkManage;
        private readonly IUserService userService;

        public TransactionController(IBaseService<Role> roleService, 
            IUnitOfWorkManage unitOfWorkManage,
            IUserService userService)
        {
            this.roleService = roleService;
            this.unitOfWorkManage = unitOfWorkManage;
            this.userService = userService;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            try
            {
                Console.WriteLine("Begin Transaction");

                //unitOfWorkManage.BeginTran();
                using var uow = unitOfWorkManage.CreateUnitOfWork();
                var roles = await roleService.Query();
                Console.WriteLine($"1 first time : the count of role is :{roles.Count}");

                Console.WriteLine("insert a data into the table role now.");
                TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                //var insertPassword = await roleService.Add(new Role()
                //{
                //    Id = timeSpan.TotalSeconds.ObjToLong(),
                //    IsDeleted = false,
                //    Name = "role name"
                //});

                var roles2 = await roleService.Query();
                Console.WriteLine($"2 second time : the count of role is :{roles2.Count}");

                int ex = 0;
                Console.WriteLine("There's an exception!!!");
                Console.WriteLine();
                int throwEx = 1 / ex;
                //unitOfWorkManage.CommitTran();
                uow.Commit();
            }
            catch (Exception ex)
            {
                var roles3 = await roleService.Query();
                Console.WriteLine($"3 third time : the count of role is : {roles3.Count}");
            }
            return Ok("OK");
        }

        [HttpGet]
        public async Task<object> TestTranPropagation()
        {
            return await userService.TestTranPropagation();
        }
    }
}
